package com.heqiang.spring.beans.factory;

import com.heqiang.spring.beans.BeansException;
import com.heqiang.spring.beans.PropertyValue;
import com.heqiang.spring.beans.PropertyValues;
import com.heqiang.spring.beans.factory.config.BeanDefinition;
import com.heqiang.spring.beans.factory.config.BeanFactoryPostProcessor;
import com.heqiang.spring.core.io.Resource;
import com.heqiang.spring.core.io.loader.DefaultResourceLoader;

import java.io.IOException;
import java.util.Properties;

public class PropertyPlaceholderConfigurer implements BeanFactoryPostProcessor {

    public static final String DEFAULT_PLACEHOLDER_PREFIX = "${";

    public static final String DEFAULT_PLACEHOLDER_SUFFIX = "}";

    private String location;


    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        try {
            DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
            Resource resource = resourceLoader.getResource(location);
            Properties properties = new Properties();
            properties.load(resource.getInputStream());

            String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
            for (String beanName : beanDefinitionNames) {
                BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);

                PropertyValues propertyValues = beanDefinition.getPropertyValues();
                for (PropertyValue propertyValue : propertyValues.getProperValues()) {
                    Object value = propertyValue.getValue();
                    if (!(value instanceof String)) {
                        continue;
                    }
                    String strValue = (String) value;
                    StringBuilder builder = new StringBuilder(strValue);
                    int startIdx = strValue.indexOf(DEFAULT_PLACEHOLDER_PREFIX);
                    int endIdx = strValue.indexOf(DEFAULT_PLACEHOLDER_SUFFIX);
                    if (startIdx != -1 && endIdx != -1 && startIdx < endIdx) {
                        String proKey = strValue.substring(startIdx+2,endIdx);
                        String proVal = properties.getProperty(proKey);
                        builder.replace(startIdx,endIdx+1,proVal);
                        propertyValues.addProperValue(new PropertyValue(propertyValue.getName(),builder.toString()));
                    }
                }
            }

        } catch (IOException e) {
            throw new BeansException("Could not load properties", e);
        }
    }


    public void setLocation(String location) {
        this.location = location;
    }
}
